package com.canieatit.app;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.Status;
import org.restlet.resource.ClientResource;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.canieatit.app.network.BingSearch;
import com.canieatit.gwt.shared.Product;
import com.canieatit.gwt.shared.ProductResource;
import com.fedorvlasov.lazylist.ImageLoader;

public class AddProductActivity extends ParentActivity implements OnClickListener{
	private static final String TAG = "AddProductActivity";
	private static final int RESULTS_PER_QUERY = 10;
	private static final String BING_SEARCH_URL = "https://api.datamarket.azure.com/Bing/Search/Image?$top="+RESULTS_PER_QUERY+"&$format=json&Query=";
	Product mProduct;
	JSONObject resultsJson;
	int index = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_product);

		Button submitButton = (Button) findViewById(R.id.button_submit);
		submitButton.setOnClickListener(this);
	
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.button_submit:
			getProductImageUrl();
			break;

		default:
			break;
		}		
	}

	private void addProduct(String imageUrl) {
		
//		ClientResource clientResource = new ClientResource("http://can-i-eat-it.appspot.com/product?barcode=1231231232&format=\"ean\"");
		
		Account[] accounts = AccountManager.get(this).getAccountsByType("com.google");
		
		
		ClientResource clientResource = new ClientResource(RESTLET_TEST_URL);
		ProductResource productResource = clientResource.wrap(ProductResource.class);
		clientResource.setEntityBuffering(true);
		
		String barcode = getIntent().getStringExtra(EXTRA_BARCODE_NUMBER);
		final EditText productName = (EditText) findViewById(R.id.productName);
		final EditText productSize = (EditText) findViewById(R.id.productSize);
		
		String productCountry = "Pakistan";
		
		mProduct = new Product(barcode, productName.getText().toString(), productCountry, productSize.getText().toString(), imageUrl, accounts[0].name);
		
		productResource.store(mProduct);
		Status status = clientResource.getResponse().getStatus();
		
		clientResource.release();
		
		if (status.equals(Status.SUCCESS_OK)) {
			Toast.makeText(this, "Product details added. Admin has been notified to review and update", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, "Could not add product. Please try again later", Toast.LENGTH_LONG).show();
		}
		
		finish();
		
	}

	private void getProductImageUrl() {
		
		final EditText productName = (EditText) findViewById(R.id.productName);
		final EditText productSize = (EditText) findViewById(R.id.productSize);
		
		final String searchQuery = productName.getText() + " " + productSize.getText();
		
		try {
			new BingSearchTask(BING_SEARCH_URL + URLEncoder.encode("'" + searchQuery + "'", "UTF-8")).execute();
		} catch (UnsupportedEncodingException e) {
			Toast.makeText(this, "Error encoding the search query", Toast.LENGTH_SHORT).show();
			Log.e(TAG, e.getMessage(), e);
			return;
		}		
	}
	
	private void onImageResults(final JSONObject result) {
		final ImageLoader mImageLoader = ((BarcoderApplication) getApplication()).getImageLoader();
		final View view = LayoutInflater.from(this).inflate(R.layout.alert_select_image, null);
		final ImageView mImageView = (ImageView) view.findViewById(R.id.imageview_product_image);
		try {
			mImageLoader.DisplayImage(result.getJSONArray("results").getJSONObject(index).getJSONObject("Thumbnail").getString("MediaUrl"), mImageView);
		} catch (JSONException e) {
			Log.e(TAG, e.getMessage(), e);
		}
		AlertDialog.Builder productImageSelectAlert = new AlertDialog.Builder(this);
		productImageSelectAlert.setTitle("Select Product Image")
		
		.setView(view)
		.setPositiveButton("Accept", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				try {
					addProduct(result.getJSONArray("results").getJSONObject(index).getJSONObject("Thumbnail").getString("MediaUrl"));
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(),e);
				}
				
			}
		});
		
		view.findViewById(R.id.button_next_image).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (index == RESULTS_PER_QUERY) {
					index = 0;
					String searchURL = null;
					try {
						
						result.getString("__next");
					} catch (JSONException e) {
						Log.e(TAG, e.getMessage(), e);
					}
					
					new BingSearchTask(searchURL+"&$format=json").execute();
				}
				
				index++;
				try {
					mImageLoader.DisplayImage(result.getJSONArray("results").getJSONObject(index).getJSONObject("Thumbnail").getString("MediaUrl"), mImageView);
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
			}
		});
		
		view.findViewById(R.id.button_previous_image).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (index == 0) {
					Toast.makeText(AddProductActivity.this, "No previous image available", Toast.LENGTH_SHORT).show();
					return;
				}
				
				index--;
				try {
					mImageLoader.DisplayImage(result.getJSONArray("results").getJSONObject(index).getJSONObject("Thumbnail").getString("MediaUrl"), mImageView);
				} catch (JSONException e) {
					Log.e(TAG, e.getMessage(), e);
				}
				
			}
		});
		
		productImageSelectAlert.show();
		
	}
	
	private class BingSearchTask extends AsyncTask<Void, Void, JSONObject> {
		String searchURL;
		
		BingSearchTask(String searchURL) {
			this.searchURL = searchURL;
		}

		@Override
		protected JSONObject doInBackground(Void... params) {
			try {
				String response = BingSearch.httpGet(searchURL);
				resultsJson = new JSONObject(response).getJSONObject("d");
			} catch (Exception e) {
				Log.e(TAG, e.getMessage(), e);
			}
			return resultsJson;
		}
			
		protected void onPostExecute(JSONObject result) {
			onImageResults(result);
		};

	}
}